/*
 * @Author: lixu lixu@puchigames.com
 * @Date: 2025-01-03 16:49:48
 * @LastEditors: lixu lixu@puchigames.com
 * @LastEditTime: 2025-09-16 17:59:04
 * @FilePath: /go-helper/ixRedis/manager.go
 * @Description: Redis 管理器相关
 */
package ixRedis

import (
	"errors"
	"fmt"
	"sync"
	"time"

	"github.com/garyburd/redigo/redis"
)

// Manager Redis 管理器
type Manager struct {
	clients map[string]*Client
	configs map[string]*Config
	mu      sync.RWMutex
	closed  bool
}

var (
	manager *Manager
	once    sync.Once
)

// NewManager 创建 Redis 管理器
func NewManager() *Manager {
	once.Do(func() {
		manager = &Manager{
			clients: make(map[string]*Client),
			configs: make(map[string]*Config),
			closed:  false,
		}
	})
	return manager
}

// GetManager 获取 Redis 管理器实例
func GetManager() *Manager {
	return NewManager()
}

// AddConfig 添加 Redis 配置
func (m *Manager) AddConfig(name string, config *Config) error {
	if m.closed {
		return errors.New("manager is closed")
	}
	if name == "" {
		return errors.New("config name cannot be empty")
	}
	if config == nil {
		return errors.New("config cannot be nil")
	}

	m.mu.Lock()
	defer m.mu.Unlock()
	m.configs[name] = config
	return nil
}

// GetClient 获取 Redis 客户端
func (m *Manager) GetClient(name string) (*Client, error) {
	if m.closed {
		return nil, errors.New("manager is closed")
	}
	if name == "" {
		return nil, errors.New("client name cannot be empty")
	}

	m.mu.RLock()
	if client, exists := m.clients[name]; exists {
		m.mu.RUnlock()
		return client, nil
	}
	m.mu.RUnlock()

	// 如果客户端不存在，创建新客户端
	m.mu.Lock()
	defer m.mu.Unlock()

	// 双重检查
	if client, exists := m.clients[name]; exists {
		return client, nil
	}

	config, exists := m.configs[name]
	if !exists {
		return nil, fmt.Errorf("config not found for client: %s", name)
	}

	client, err := m.createClient(config)
	if err != nil {
		return nil, err
	}

	m.clients[name] = client
	return client, nil
}

// createClient 创建 Redis 客户端
func (m *Manager) createClient(config *Config) (*Client, error) {
	// 构建连接地址
	address := fmt.Sprintf("%s:%d", config.Host, config.Port)

	// 创建连接池
	pool := &redis.Pool{
		MaxIdle:     config.MaxIdle,
		MaxActive:   config.MaxActive,
		IdleTimeout: config.IdleTimeout,
		Wait:        config.Wait,
		Dial: func() (redis.Conn, error) {
			conn, err := redis.Dial("tcp", address,
				redis.DialConnectTimeout(config.ConnectTimeout),
				redis.DialReadTimeout(config.ReadTimeout),
				redis.DialWriteTimeout(config.WriteTimeout),
			)
			if err != nil {
				return nil, err
			}

			// 认证
			if config.Password != "" {
				if _, err := conn.Do("AUTH", config.Password); err != nil {
					conn.Close()
					return nil, err
				}
			}

			// 选择数据库
			// 无论DB是否为0，都执行SELECT命令来确保数据库状态正确
			if _, err := conn.Do("SELECT", config.DB); err != nil {
				conn.Close()
				return nil, err
			}

			return conn, nil
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			if time.Since(t) < time.Minute {
				return nil
			}
			// 检查连接是否可用
			_, err := c.Do("PING")
			if err != nil {
				return err
			}
			// 确保连接在正确的数据库中
			// 无论DB是否为0，都需要执行SELECT命令来确保数据库状态正确
			_, err = c.Do("SELECT", config.DB)
			if err != nil {
				return err
			}
			return nil
		},
	}

	// 测试连接
	conn := pool.Get()
	defer conn.Close()
	if _, err := conn.Do("PING"); err != nil {
		pool.Close()
		return nil, fmt.Errorf("failed to connect to redis: %w", err)
	}

	return &Client{
		pool:   pool,
		config: config,
		closed: false,
	}, nil
}

// Close 关闭所有 Redis 连接
func (m *Manager) Close() error {
	if m.closed {
		return nil
	}

	m.mu.Lock()
	defer m.mu.Unlock()

	for name, client := range m.clients {
		if client != nil {
			client.Close()
		}
		delete(m.clients, name)
	}

	m.closed = true
	return nil
}
